//
//  CHDDetailsVC.m
//  IOSWeiiPhoneNews
//
//  Created by ibokan on 14-4-24.
//  Copyright (c) 2014年 chen. All rights reserved.
//

#import "CHDDetailsVC.h"
#import "TFHpple.h"


@interface CHDDetailsVC ()

@end

@implementation CHDDetailsVC

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    //NSLog(@"%@",self.authorr);
    //初始化用于接收一段内容的可变字符串
    self.contentString=[[NSMutableString alloc]init];
    //初始化用来存放解析下来的JSON数据的字典
    self.dic=[[NSMutableDictionary alloc]init];
    //把自动布局设为NO
    self.automaticallyAdjustsScrollViewInsets=NO;
    
    //设置导航栏的标题
    self.title=@"新闻详情";
    //设置导航栏的rightBarButtonItem,并给其一个单击事件用来收藏该条新闻
    UIBarButtonItem *rightButton = [[UIBarButtonItem alloc]initWithBarButtonSystemItem:UIBarButtonSystemItemOrganize target:self action:@selector(collect)];
    self.navigationItem.rightBarButtonItem = rightButton;
    //设置大scrollview能否翻页
    self.scrolView.pagingEnabled=YES;
    //设置大scrollview能否进行用户交互
    self.scrolView.userInteractionEnabled=YES;

    
    //初始化存放新闻标题的label
    self.labelTitle=[[UILabel alloc]initWithFrame:CGRectMake(10,10,300,60)];
    //自动换行
    self.labelTitle.numberOfLines=0;
    //设置label的尺寸
    self.labelTitle.font=[UIFont systemFontOfSize:24];
    //设置label的颜色
    self.labelTitle.textColor=[UIColor blueColor];
    [self.scrolView addSubview:self.labelTitle];
    //内容发表时间
    self.labeltime=[[UILabel alloc]initWithFrame:CGRectMake(10, 110, 110, 30)];
    //字体
    self.labeltime.font=[UIFont systemFontOfSize:13];
    self.labeltime.text=self.timeStr;
    //隐藏
    self.labeltime.hidden=YES;
    [self.scrolView addSubview:self.labeltime];
    //初始化用来存放新闻来源的label
    self.labelSource=[[UILabel alloc]initWithFrame:CGRectMake(130, 110, 80, 30)];
    self.labelSource.font=[UIFont systemFontOfSize:13];
    self.labelSource.hidden=YES;
    [self.scrolView addSubview:self.labelSource];
    //作者
    self.labelAuthor=[[UILabel alloc]initWithFrame:CGRectMake(220, 110, 100, 30)];
    self.labelAuthor.font=[UIFont systemFontOfSize:13];
    self.labelAuthor.text=[NSString stringWithFormat:@"作者:%@",self.authorr];
    self.labelAuthor.hidden=YES;
    [self.scrolView addSubview:self.labelAuthor];
    //初始化评论按钮
    self.button=[[UIButton alloc]initWithFrame:CGRectMake(230,70,80,40)];
    //给评论按钮添加一张背景图片
    [self.button setBackgroundImage:[UIImage imageNamed:@"home_tab_icon_22"] forState:UIControlStateNormal];
    //self.button.titleLabel.font = [UIFont systemFontOfSize:17];
    [self.button setTitleColor:[UIColor blueColor] forState:UIControlStateNormal];
    [self.button addTarget:self action:@selector(evaluate) forControlEvents:UIControlEventTouchDown];
    self.button.hidden=YES;
    [self.scrolView addSubview:self.button];

    //imgScrollView
    self.imgScrollView = [[UIScrollView alloc] init];
    self.imgScrollView.frame=CGRectMake(0, 150, 320, 180);
    //设置代理
    self.imgScrollView.delegate=self;
    //是否显示边上拉条
    self.imgScrollView.showsHorizontalScrollIndicator=NO;
    //能否翻页
    self.imgScrollView.pagingEnabled=YES;
    //用户交互
    self.imgScrollView.userInteractionEnabled=YES;
    //能否滚动
    self.imgScrollView.scrollEnabled = YES;

    [self.scrolView addSubview:self.imgScrollView];

    [self performSelector:@selector(downShowData)];
}
-(void)downShowData
{
    [self showHUD];
    NSURL *url=[NSURL URLWithString:self.urlStr];
    NSURLRequest *request=[NSURLRequest requestWithURL:url];
    [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue currentQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
        
        //获取文章标题
        TFHpple *xpathParser=[[TFHpple alloc]initWithHTMLData:data];
        NSArray *arrContent = [xpathParser searchWithXPathQuery:@"//div[@class='content_main']//h1"];
        for (int i=0; i <arrContent.count; i++) {
            TFHppleElement *element =[arrContent objectAtIndex:i];
            NSString *myContent = [element content];
            self.labelTitle.text = myContent;
        }
        //获取文章来源标题
        NSArray *arrSource = [xpathParser searchWithXPathQuery:@"//div[@class='content_main']//div[@class='content_header']//div[@class='author']//span"];
        for (int i=0; i <arrSource.count; i++) {
            TFHppleElement *element5 =[arrSource objectAtIndex:i];
            NSString *myContent5 = [element5 content];
            if (i%2!=0) {
                self.labelSource.text=myContent5;
            }
        }
        //获取文章图片
        NSArray *arrContent3 = [xpathParser searchWithXPathQuery:@"//div[contains(concat(' ', @class, ' '), ' content_text ')]//p//img//@src"];
        self.k=(int)arrContent3.count;//判断图片多少张
        for (int i=0; i <arrContent3.count; i++) {
            TFHppleElement *element3 =[arrContent3 objectAtIndex:i];
            NSString *myContent3 = [element3 content];
            self.imageView= [[EGOImageView alloc] initWithPlaceholderImage:[UIImage imageNamed:@"1.jpg"]];
            [self.imageView setFrame:CGRectMake(320*i,0, 320, 180)];
            self.imgScrollView.contentSize=CGSizeMake(320*(i+1), 180);
            [self.imageView setImageURL:[NSURL URLWithString:myContent3]];
            [self.imgScrollView addSubview:self.imageView];
        }
        self.page=[UIPageControl new];
        self.page.frame=CGRectMake(160, 310, 120, 30);
        self.page.currentPageIndicatorTintColor=[UIColor grayColor];
        self.page.backgroundColor=[UIColor clearColor];
        self.page.numberOfPages=arrContent3.count;
        self.page.currentPage=0;
        [self.scrolView addSubview:self.page];
        
        
        //获取文章内容
        NSArray *arrContent2 = [xpathParser searchWithXPathQuery:@"//div[contains(concat(' ', @class, ' '), ' content_text ')]//text()|span"];
        if (arrContent2.count<=0) {
            UIAlertView*alert=[[UIAlertView alloc]initWithTitle:@"注意" message:@"当前点击页面内容为空！" delegate:self cancelButtonTitle:@"返回" otherButtonTitles:@"取消", nil];
            [alert show];
        }else{
            
            for (int i=0; i <arrContent2.count; i++)
            {
                TFHppleElement *element2 =[arrContent2 objectAtIndex:i];
                NSString *myContent2 = [element2 content];
                //NSLog(@"%@",myContent2);
                NSString * str =  [myContent2 stringByReplacingOccurrencesOfString:@"\t" withString:@""];
                
                if ([str isEqualToString:@"以下为文章全文："])
                {
                    continue;
                }
                if ([str isEqualToString:@"[文章纠错]"])
                {
                    continue;
                }
                if (![str isEqualToString:@"分享到："])
                {
                    self.contentString = (NSMutableString *)[self.contentString stringByAppendingFormat:@"\n%@",str];
                }else
                {
                    continue;
                }
            }
        }
        
        //IOS自定义label高度新方法
        NSDictionary *dic = @{NSFontAttributeName:[UIFont systemFontOfSize:17.0]};
        CGRect rect = [self.contentString boundingRectWithSize:CGSizeMake(300, 4000) options:NSStringDrawingTruncatesLastVisibleLine|NSStringDrawingUsesLineFragmentOrigin|NSStringDrawingUsesFontLeading attributes:dic context:nil];
        self.labelContent=[[UILabel alloc]initWithFrame:CGRectMake(0, 240,320, rect.size.height)];
        self.labelContent.text = self.contentString;
        self.labelContent.numberOfLines=0;
        [self.scrolView addSubview:self.labelContent];
        self.scrolView.contentSize=CGSizeMake(320, 100+rect.size.height);
        
        //获取评论的数据
        NSString*newAddress=[self fanzhuan:self.urlStr];
        NSString*idAndFrom=[newAddress substringFromIndex:6];
        NSString*idAdress=[idAndFrom substringToIndex:6];
        NSString*commentId=[self fanzhuan:idAdress];
        
        NSURL * commentUrl = [NSURL URLWithString:[NSString stringWithFormat:@"http://www.weiphone.com/publish/comment_v3.php?article_id=%@",commentId]];
        NSURLRequest * commentRequest = [NSURLRequest requestWithURL:commentUrl];
        //将请求的url数据放到NSData对象中
        //            NSData *commentReq= [NSURLConnection sendSynchronousRequest:commentRequest returningResponse:nil error:nil];
        [NSURLConnection sendAsynchronousRequest:commentRequest queue:[NSOperationQueue currentQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
            //IOS5自带解析类NSJSONSerialization从response中解析出数据放到字典中
            self.dic= [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:&connectionError];
            NSArray*ary=[NSArray arrayWithArray:[self.dic objectForKey:@"list"]];
            [self.button setTitle:[NSString stringWithFormat:@"%d",(int)ary.count] forState:UIControlStateNormal];
            self.button.hidden=NO;
            self.labelAuthor.hidden=NO;
            self.labeltime.hidden=NO;
            self.labelSource.hidden=NO;
            [self hideHUD];
        }];
        
        
    }];
}
//警告框返回方法，实现UIAlertViewDelegate代理方法
-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
    
    if (buttonIndex==0) {
        [self.navigationController popViewControllerAnimated:NO];
    }
}
-(void)collect{
    //将标题 网址保存到数组
    self.arry=[[NSMutableArray alloc]initWithObjects:self.labelTitle.text,self.urlStr,self.labelAuthor.text,self.labeltime.text,nil];
    

    //获取document下的路径
    NSString*documents=[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)objectAtIndex:0];
    self.path=[documents stringByAppendingPathComponent:@"News.plist"];
    //获取获取document下的NewsConformation.plist文件中得数据
    NSMutableArray*originalAry=[[NSMutableArray alloc]initWithContentsOfFile:self.path];
    //判断是否存在数据 没有 则从本地资源获取
    if (originalAry.count<=0) {
        originalAry=[NSMutableArray arrayWithContentsOfFile:[[NSBundle mainBundle]pathForResource:@"news" ofType:@"plist"]];
    }
//    //通过遍历数组看添加的网址是否已经存在，存在则不添加
//    for (int i=0; i<originalAry.count; i++) {
//        NSMutableArray *arry3=[[NSMutableArray alloc]initWithCapacity:5];
//        arry3=[originalAry objectAtIndex:i];
//        NSString *string1=[[NSString alloc]initWithFormat:@"%@",[arry3 objectAtIndex:0]];
//        if ([self.labelTitle.text isEqualToString:string1])
//        {
//            self.navigationItem.rightBarButtonItem.enabled=NO;
//        }
//    }
        //增加当前加入的
        [originalAry addObject:self.arry];
        UIAlertView *view=[[UIAlertView alloc]initWithTitle:@"系统消息" message:@"恭喜您添加成功" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:@"取消", nil];
        [view show];
    //写入文件
    [originalAry writeToFile:self.path atomically:YES];
    //取消按钮的交互
    self.navigationItem.rightBarButtonItem.enabled=NO;
}

-(void)evaluate
{
//    //跳转到查看评论界面，将json解析的字典通过关键字获得一个数组一并存入下一个界面
//    EvaluateViewController *ev=[[EvaluateViewController alloc]init];
//    ev.arry=[NSMutableArray arrayWithArray:[self.dic objectForKey:@"list"]];
//    [self.navigationController pushViewController:ev animated:YES];
    
}


- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
//翻转字符串
-(NSString*)fanzhuan:(NSString*)str{
    //创建无符号long型
    unsigned long len;
    //求字符串长度
    len = [str length];
    //unichar是两字节长的char 代表unicode的一个字符
    unichar a[len];
    for(int i = 0; i < len; i++)
    {
        unichar c = [str characterAtIndex:len-i-1];
        a[i] = c;
    }
    NSString *str1=[NSString stringWithCharacters:a length:len];
    return str1;
}

-(void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    for (int i=0; i<self.k; i++) {
        if (self.imgScrollView.contentOffset.x==i*320) {
            self.page.currentPage=i;
        }
    }
    
}

@end
